// src/main/java/com/booking/springrestful/controller/AskController.java
package com.booking.springrestful.controller;

import com.booking.springrestful.domain.dto.AskRequest;
import com.booking.springrestful.service.LargeModelService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/largeModel")
@RequiredArgsConstructor
public class AskController {

    private final LargeModelService largeModelService;

    @PostMapping("/ask")
    public void ask(@RequestBody AskRequest request, HttpServletResponse response) throws IOException {
        // ✅ 设置为 Server-Sent Events (SSE) 格式
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        // 可选：允许跨域（如果前端跨域）
        // response.setHeader("Access-Control-Allow-Origin", "*");

        String question = request.getQuestion();
        if (question == null || question.trim().isEmpty()) {
            response.getWriter().write("data: 问题不能为空\n\n");
            response.flushBuffer();
            return;
        }

        try {
            largeModelService.streamAnswer(question.trim(), chunk -> {
                try {
                    // ✅ SSE 格式：data: 内容\n\n
                    response.getWriter().write("data: " + chunk + "\n\n");
                    response.flushBuffer(); // ⚠️ 强制刷新缓冲区
                } catch (IOException e) {
                    throw new RuntimeException("写入响应流失败", e);
                }
            });
        } catch (Exception e) {
            // 发送错误消息（也按 SSE 格式）
            try {
                response.getWriter().write("data: 生成失败：" + e.getMessage() + "\n\n");
                response.flushBuffer();
            } catch (IOException ignored) {}
        }
        // ⚠️ 不要 close()，由容器管理；否则可能中断流
    }
}